package com.yuan.homework.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @program: Train
 * @description: LoginServlet
 * @author: yuan_boss
 * @create: 2022-11-21 17:57
 **/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        //是否重复登录的标志，该列表只存一个值
        List<Integer> flag =(List<Integer>)this.getServletContext().getAttribute("flag");
        if ("login".equals(action)){
            String name = req.getParameter("username");
            if (name != null && !"".equals(name)){
                req.getSession().setAttribute("loginUser",name);
                req.setAttribute("msg","登录成功");
                System.out.println("登陆成功");
            }else {
                req.setAttribute("msg","请输入用户名再登录");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
                return;
            }
            if (flag.get(0)==1){
                req.setAttribute("repeat","用户: " + name + " 重复登录");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
                //把标志还原为0，以免其他用户登录变成重复登录
                flag.set(0,0);
                return;
            }
            req.getRequestDispatcher("main.jsp").forward(req,resp);
        }else if ("logout".equals(action)){
            System.out.println("用户退出");
            req.getSession().invalidate();
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
